<template>
<div>
  <!-- 搜索框+添加用户 -->
  <el-row :gutter="20">
    <el-col :span="8">
 <!-- 搜索框 -->
    <el-input
            placeholder="请输入用户ID"
            v-model="searchcontent"
            clearable
            @clear="getuserlist"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getsearchuserlist"
            ></el-button> </el-input
        >
    </el-col>
    <el-col :span="4">
      <!-- 添加用户 -->

   <el-button type="primary" @click="addvisible = true">
            添加用户
  </el-button>
    </el-col>
  </el-row>
 
  
 <!-- 表格 -->

  <el-table :data="userlist" border stripe>
        <!-- 添加索引 加入type index就可以了 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column label="ID">
          <template slot-scope="scope">
            <span>{{scope.row.id}}</span>
          </template>
           </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="phone"> </el-table-column>
         <el-table-column label="头像">
           <template slot-scope="scope">
             <img :src="imgchang(scope.row.img)" width="100px" height="100px"/>
           </template>
            </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEdit(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUser(scope.row.id)"
            ></el-button>
         
          </template>
        </el-table-column>
  </el-table> 
    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next,jumper"
        :total="total"
      >
      </el-pagination>
      <!--表格修改信息弹出框  -->
        <el-dialog
      title="修改信息"
      :visible.sync="editvisible"
      width="50%"
      @close="editclosed"
    >
    <!-- 表单 -->
      <el-form
        :model="edditForm"
        :rules="edditFormRules"
        ref="edditFormRef"
        label-width="70px"
      >
        <el-form-item label="ID">
          <el-input v-model="edditForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="edditForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="edditForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- 底部的确认和取消 -->
        <el-button @click="editvisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserinfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户弹出框 -->
        <el-dialog
      title="添加用户"
      :visible.sync="addvisible"
      width="50%"
      @close="addclosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="70px"
      >
      <!-- 头像上传 -->
      <el-upload
  class="avatar-uploader"
  action="/app/login/uploadimg"
  :show-file-list="true"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload"
  
 >
  <img v-if="imageUrl"  :src="imageUrl" class="avatar" >
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
        <el-form-item label="用户名" prop="id">
          <el-input v-model="addForm.id"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addvisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
</div>

    
  
</template>

<script>
export default{
  data(){
    //验证邮箱是否符合规范
    var checkEmail = (rule, value, cb) => {
      const regEmail =
        /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法邮箱号"));
    };
    //验证手机号
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法手机号"));
    };
    return{
      userlist:[],
      total:5,
      // mmm:require("../../server/upload/2b62a85dc881d7731a21d602e7482c93banner_right.png"),
     searchcontent:"",
     pagenum:1,//前往第几页
      pagesize:2,//一页的数据有多少条
      editvisible:false,//修改信息弹出框
      edditForm:{},
      edditFormRules:{
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile,trigger: "blur" },
        ],
      },
      addvisible:false,
      addForm:{
    id: "",
        password: "",
        email: "",
        phone: "",
        img:""
        },
        // 表格图片显示
        // imgpic:[],
      //表单验证规则
      addFormrules: {
        id: [
          // 第一个，必须输入用户名，在blur的时候触发
          { required: true, message: "请输入ID", trigger: "blur" },
          //第二个，必须控制长度，在blur的时候触发
          { min: 3, max: 10, message: "用户名的长度在3~10个字符之间" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          //第二个，必须控制长度，在blur的时候触发
          { min: 6, max: 15, message: "用户名的长度在6~15个字符之间" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      imageUrl:''
    }
  },
  created(){
    this.getuserlist();
  },
  methods:{
    // 获取用户列表信息
getuserlist(){
  
  this.$axios.get("/app/login/users",
  {
    params:{
      pagesize:this.pagesize,
      pagenum:this.pagenum,
      
    }
  }).then((res)=>{
    // console.log(res);
    this.userlist=res.data.result;
    // console.log(this.userlist)
    this.total=res.data.resulti[0].num;
    //解决图片不显示的问题
    // this.imgpic=require("../../server/upload/2b62a85dc881d7731a21d602e7482c93banner_right.png")
  })
},
// 获取搜索的结果
getsearchuserlist(){
 
  this.$axios.get("/app/login/search",
  {
    params:{
   
      searchcontent:this.searchcontent
    }
  }).then((res)=>{
  // console.log(res);
    // this.userlist=res.data.result;
    this.userlist=res.data;
    this.total=1;
    })
},
handleSizeChange(newsize){
  // console.log(newsize);
  this.pagesize=newsize;
  this.getuserlist();
},
  handleCurrentChange(newPage) {
    
      this.pagenum = newPage;
      this.getuserlist();
},

  // 删除用户
  removeUser(number){
      const confirmResult =  this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(()=>{
          this.$axios.get("/app/login/del",{
            params:{
              userid:number
            }
            }).then((res)=>{
             this.$message.success("删除用户成功");   
              this.$router.go(0);//页面重新加载一次
        this.getuserList();
      
        })
      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });

        
     
      
      
  },
  // 关闭之后重置表单
  editclosed(){
      this.$refs.edditFormRef.resetFields();
  },
  // 页面打开显示的默认信息
  showEdit(numedit){
    this.$axios.get("/app/login/useredit",{
      params:{
        uu:numedit
      }
    }).then((res)=>{
    //  console.log(res);
      this.edditForm=res.data.result[0];
      this.editvisible=true;
    })
  },
  // 编辑点击确定之后
  editUserinfo(){
    this.$refs.edditFormRef.validate((valid)=>{
      if (!valid) return;
      this.$axios.post("/app/login/edituser",{
        email:this.edditForm.email,
        phone:this.edditForm.phone,
        userid:this.edditForm.id       
      }).then((res)=>{
     //   console.log(res);
        this.getuserlist();
        this.editvisible=false;
        this.$message.success("更新信息成功");
      })
    })
  },
addclosed(){
  this.$refs.addFormRef.resetFields();
},
// 添加用户
addUser(){
    this.$refs.addFormRef.validate( (valid) => {
      if (!valid) return;
      this.$axios.post("/app/login/adduser",{
        id:this.addForm.id,
        phone:this.addForm.phone,
        password:this.addForm.password,
        email:this.addForm.email,
        img:this.addForm.img
      }).then((res)=>{
        this.$message.success("添加成功");
        this.addvisible = false;
        this.getuserlist();
      })
    })
},
// 文件上传要求
beforeAvatarUpload(file){
 const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isPNG) {
          this.$message.error('上传头像图片只能是 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }

        return isPNG && isLt2M;
      },
// 文件上传成功
 handleAvatarSuccess(res, file) {
      // console.log(res);
      // console.log(file);
       this.imageUrl = URL.createObjectURL(file.raw);
      this.addForm.img=res.imgUrl;
       //  console.log( this.addForm.img)
      },
      // 图片转换
      imgchang(name){
    //    console.log(name)     
      if(name==null||name==undefined||name==""){
        return require("../assets/original.png")
      }else{ 
      let xx= require("../../server/upload/"+name);
      return xx;
      }
      }
}
}
</script>
<style scoped>
 .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    margin-bottom: 20px;
  }
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
 .el-icon-plus{
   position: absolute;
  top:45px;
  left: 45px;
  
 }
 .avatar{
   width: 100px;
   height: 100px;
 }
</style>